import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
import { v4 as uuidv4 } from 'uuid';

export type UserDocument = HydratedDocument<User>;
export type UserRole = 'admin' | 'normal';

@Schema({
  timestamps: true,
  toJSON: {
    transform(doc, ret) {
      delete ret.password;
      delete ret.__v;
      if (ret.createdAt) {
        ret.createdAt = new Date(ret.createdAt).toLocaleString('zh-CN', {
          timeZone: 'Asia/Shanghai',
        });
      }
      if (ret.updatedAt) {
        ret.updatedAt = new Date(ret.updatedAt).toLocaleString('zh-CN', {
          timeZone: 'Asia/Shanghai',
        });
      }
      return ret;
    },
  },
})
export class User {
  @Prop({ required: true, unique: true, default: uuidv4 })
  id: string;

  //   手机号，邮箱，或者是
  // Oauth Provider + ID，eg：Gitee123456
  @Prop({ required: true, unique: true })
  username: string;

  // 加密存储。只有邮箱注册登录的时候是需要的
  @Prop()
  password?: string;

  @Prop()
  nickName?: string;

  // 头像图片 url
  @Prop()
  picture?: string;

  @Prop()
  phoneNumber?: string;

  @Prop()
  city?: string;

  // 账户类型（邮箱，手机 oatuh）
  @Prop({ enum: ['email', 'cellphone', 'oauth'], default: 'email' })
  type?: string;

  // oauth 提供方
  @Prop({ enum: ['gitee', 'github', 'weixin'] })
  provider?: string;

  @Prop()
  oauthID?: string;

  @Prop({ default: 'normal' })
  role?: UserRole;
}

export const UserSchema = SchemaFactory.createForClass(User);
